﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Hicap.AuthorizationServer.Application.Dto;
using Hicap.AuthorizationServer.Core.Managers;
using Hicap.AuthorizationServer.Core.Models;
using Microsoft.EntityFrameworkCore;

namespace Hicap.AuthorizationServer.Application.Sys
{
    public class UserRoleRelatedAppService : AuthorizationServerApplicationBase<UserRoleRelated, UserRoleRelatedListDto, UserRoleRelatedEditDto>
    {
        private readonly IUserRoleRelatedManager _manager;

        public UserRoleRelatedAppService(IUserRoleRelatedManager manager)
        : base(manager)
        {
            _manager = manager;
        }

        /// <summary>
        /// 按照固定条件查询关系表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<UserRoleRelatedListDto>> PagedQueryDatasAsync(UserRoleRelatedQueryDTO input)
        {
            Func<UserRoleRelated, bool> query = (entity) =>
            {
                var flag = true;
                if (input.RoleId.HasValue) flag = entity.RoleId == input.RoleId && flag;
                if (input.UserId.HasValue) flag = entity.UserId == input.UserId && flag;
                if (!string.IsNullOrEmpty(input.UserCode)) flag = entity.User != null && (entity.User.UserCode == input.UserCode && flag);
                if (!string.IsNullOrEmpty(input.RoleCode)) flag = entity.User != null && (entity.Role.RoleCode == input.RoleCode && flag);
                if (!string.IsNullOrEmpty(input.UserName)) flag = entity.User != null && (entity.User.UserName.Contains(input.UserName) && flag);
                if (!string.IsNullOrEmpty(input.RoleName)) flag = entity.User != null && (entity.Role.RoleName.Contains(input.RoleName) && flag);
                return flag;
            };

            var count = await _manager.GetCount(query);

            var result = await _manager.GetRoleAllIncluding().Where(x => query(x))
                .OrderBy(input.Sorting)
                .PageBy(input)
                .ToListAsync();

            var resultListDto = result.MapTo<List<UserRoleRelatedListDto>>();

            return new PagedResultDto<UserRoleRelatedListDto>(
                count,
                resultListDto
            );
        }
    }
}